package io.yx.flx.handler.upload;

import cn.hutool.http.Header;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import io.vertx.core.Handler;
import io.vertx.ext.web.RoutingContext;
import io.yx.flx.aspect.UploadProxy;
import io.yx.flx.service.UploadService;
import io.yx.flx.service.UploadServiceImpl;
import net.sf.cglib.proxy.Enhancer;

/**
 * 上传不压缩图片路由
 */
public class UploadNotCompressHandler implements Handler<RoutingContext> {

    private static final Log log = LogFactory.get();

    private final UploadService uploadService;

    public UploadNotCompressHandler() {
        Enhancer enhancer = new Enhancer();
        // 设置要被代理的类
        enhancer.setSuperclass(UploadServiceImpl.class);
        // 设置回调具体代理的逻辑
        enhancer.setCallback(new UploadProxy());
        enhancer.setClassLoader(UploadServiceImpl.class.getClassLoader());
        // 创建代理类并强制转化为需要的类
        this.uploadService = (UploadServiceImpl) enhancer.create();
    }

    @Override
    public void handle(RoutingContext rc) {
        // 使用代理类执行upload
        try {
            String upload = uploadService.uploadNoCompress(rc);
            rc.response().putHeader(Header.CONTENT_TYPE.getValue(), "application/json").end(upload);
        } catch (Exception e) {
            log.error(e);
            throw e;
        }
    }
}
